import { loginByPwd, getUserInfoByToken, getCosTempToken } from '@/api/admin_user'
import lodash from 'lodash'
import CONST from '@/utils/const'
import router from '@/router'
import { constantRoutes, variableRoutes, resetRouter } from '@/router'
import COS from 'cos-js-sdk-v5'

function getDefaultState() {
  return {
    token: localStorage.getItem(CONST.TOKEN_KEY),
    userInfo: null,
    routes: [],
    // cosToken: localStorage.getItem(CONST.COS_TOKEN_KEY),
    cosInstance: null
  }
}

export default {
  namespaced: true,
  state: getDefaultState(),
  mutations: {
    SET_TOKEN: (state, val) => {
      if (state.token !== val) {
        state.token = val
        localStorage.setItem(CONST.TOKEN_KEY, val)
      }
    },
    // SET_COS_TOKEN: (state, val) => {
    //   state.cosToken = val
    //   localStorage.setItem(CONST.COS_TOKEN_KEY, val)
    // },
    SET_COS_INSTANCE: (state, val) => {
      state.cosInstance = val
    },
    REMOVE_TOKEN: (state) => {
      state.token = ''
      localStorage.removeItem(CONST.TOKEN_KEY)
    },
    SET_USER_INFO: (state, val) => {
      state.userInfo = val
    },
    SET_ROUTES: state => {
      // 拷贝一份动态路由模块
      const _routes = lodash.cloneDeep(variableRoutes)

      // 筛选出该用户有权限的所有路由模块
      const otherRoutes = _routes.filter(item1 => {
        // item1.children = item1.children.filter(item2 => state.userInfo.access[item2.name])
        // return item1.children.length
        return true
      })
      console.log(otherRoutes)
      // 添加到路由中
      router.addRoutes([
        ...otherRoutes,
        { path: '*', redirect: '/404' }
      ])

      // 更新vuex 中的路由规则
      state.routes = [
        ...constantRoutes,
        ...otherRoutes,
        { path: '*', redirect: '/404' }
      ]
    },
    RESET_STATE: (state) => {
      Object.assign(state, getDefaultState())
    }
  },
  actions: {
    async login({ commit }, val) {
      const user = await loginByPwd(val)
      console.log(user)
      commit('SET_USER_INFO', user)
    },
    async newCos({ commit, state }) {
      if (state.cosInstance) return
      const cosInstance = new COS({
        getAdminAuthorization: async function(options, callback) {
          const res = await getCosTempToken()
          callback(res)
        }
      })
      commit('SET_COS_INSTANCE', cosInstance)
    },
    async getAdminUserInfo({ commit }) {
      const res = await getUserInfoByToken()
      commit('SET_USER_INFO', res)
    },

    logout({ commit, state }) {
      commit('RESET_STATE')
      commit('REMOVE_TOKEN')
      resetRouter()
      router.push('/login')
    }

  }
}

